<?php

namespace App\Http\Controllers\EmberApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class BlocksController extends Controller
{
    //
    public function index(){
        $cache = Redis::get('xdagpoolblocks');
        $stats = json_encode([]);
        if(!isset($cache)){
            $stats = $this->getData();
            Redis::setex('xdagpoolblocks',60,$stats);
            $stats = json_decode($stats);
        }else{
            $stats = json_decode($cache);
        }
        return response()->json($stats);
    }

    protected function getData(){
        $blocksCount = DB::table('found_blocks')->count();
        //var_dump($blocksCount);
        $latestBlocks = DB::table('found_blocks')
            ->latest('found_at')
            ->limit(100)
            ->get();
        $jsonArray = [];
        $jsonArray['maturedTotal'] = $blocksCount;
        $blocks = [];
        $i = 0;
        foreach ($latestBlocks as $latestBlock) {
            $blocks[$i] = [];
            $blocks[$i]['address'] = $latestBlock->address;
            $blocks[$i]['timestamp'] = strtotime($latestBlock->found_at);
            $blocks[$i]['hash'] = $latestBlock->hash;
            $blocks[$i]['reward'] = (float)$latestBlock->payout + (float)$latestBlock->fee;
            $i++;
        }
        $jsonArray['matured'] = $blocks;
        //var_dump($jsonArray);
        //return response()->json($jsonArray);
        return json_encode($jsonArray);
    }
}
